package com.ai.chinamobileai.service.impl;


import com.ai.chinamobileai.dto.ChatDTO;
import com.ai.chinamobileai.service.ChatService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.QuestionAnswerAdvisor;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.time.LocalDateTime;

/**
 * @author
 * @version V1.0
 * @date 2025-04-20 10:14
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class ChatServiceImpl implements ChatService {


    private final ChatClient chatClient;

    /**
     * 向量存储服务，用于持久化文档向量
     */
    private final VectorStore vectorStore;


    /**
     * 流式聊天
     * @param chatDTO
     * @return
     */
    @Override
    public Flux<String> chatStream(ChatDTO chatDTO) {
        // 创建搜索请求，用于搜索相关文档
        var searchRequest = SearchRequest.builder()
                .query(chatDTO.getQuestion()) // 设置查询条件
                .topK(3) // 设置最多返回的文档数量
                .build();

        return chatClient.prompt()
                .advisors(advisor -> advisor
                        .advisors(new QuestionAnswerAdvisor(vectorStore, searchRequest)) // 设置RAG的Advisor
                        .param(AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY, chatDTO.getSessionId()))
                .user(chatDTO.getQuestion())
                .stream()
                .content()
                .doOnNext(content -> log.info("question: {}, content: {}", chatDTO.getQuestion(), content))
                .concatWith(Flux.just("[END]"));
    }

}
